import datetime

import jwt
from django.conf import settings

key = settings.SECRET_KEY


class JwtUtils:
    @staticmethod
    def getToken(user_id):
        payload = {
                    'user_id': str(user_id),  # ✅ 将 UUID 转为字符串
            'exp': datetime.datetime.now() + datetime.timedelta(minutes=30)
        }
        token = jwt.encode(payload, key, algorithm='HS256')
        return 'Bearer ' + token

    @staticmethod
    def parseJwt(token):
        token = token.replace('Bearer ', '')
        try:
            return jwt.decode(token, key, algorithms='HS256')
        except jwt.exceptions.DecodeError:
            raise Exception('token 解析错误')
        except jwt.exceptions.ExpiredSignatureError:
            raise Exception('token 已过期')
        except jwt.exceptions.InvalidTokenError:
            raise Exception('token 无效')

    @staticmethod
    def getUserId(token):
        return JwtUtils.parseJwt(token)['userId']

jwtUtils = JwtUtils()

